package p5.code;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class StringSafeTest {

    public static int clientTotal = 5000;
    public static int threadTotal = 200;

    public static StringBuilder stringBuilder = new StringBuilder();
    public static StringBuffer stringBuffer = new StringBuffer();

    public static void main(String[] args) throws InterruptedException {
        //新建线程池
        ExecutorService executorService= Executors.newCachedThreadPool();
        //信号量
        final Semaphore semaphore = new Semaphore(threadTotal);
        //阻塞倒计数
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for(int i=0;i<clientTotal;i++){

            executorService.execute(()->{
                try{
                    semaphore.acquire();
                    Mothen();
                    semaphore.release();
                }catch(Exception e){
                    e.printStackTrace();
                }
                countDownLatch.countDown();//计数器减一操作
            });
        }
        countDownLatch.await();//阻塞线程
        executorService.shutdown();//其中先前提交的任务将被执行，但不会接受任何新任务
        System.out.println("stringBuilder.length: "+stringBuilder.length());
        System.out.println("stringBuffer.length: "+stringBuffer.length());
    }
    public static void Mothen() {
        stringBuilder.append("i");
        stringBuffer.append("o");
    }


}
